import React, { useEffect, useRef, useState } from 'react'
import { Form, Input, Radio, Button, Space, InputNumber, Modal, message } from 'antd'
import TheLocations from '@/components/TheLocations';
import { useLocation } from 'react-router-dom';
import { freightTemplateDetails, freightTemplateAddOrEdit } from '@/api/goodsManagement/freightTemplate.js';
import { apiStoreInfo } from '@/api/login/index.js'
import { Decimal } from 'decimal.js';
import TheButton from "@/components/TheButton/index.jsx";
import GoBack from "@/components/TheGoBack";
import { useNavigate } from 'react-router-dom';

export default function FreightTemplate() {
  const location = useLocation(); //参数以及路由地址
  const navigate = useNavigate();

  const formRef = useRef()
  const areaRef = useRef()
  const freightTemplateId = location.state.freightTemplateId //运费模板id
  const mode = location.state.mode //预览模式
  const [cityModal, setCityModal] = useState(false)
  const [selectArea, setSelectArea] = useState({}) //选中的
  const [city, setCity] = useState() //文案回显
  const [loading, setLoading] = useState(false)
  const [isProprietary, setIsProprietary] = useState('N')
  const getData = async () => {
    await freightTemplateDetails({
      freightTemplateId
    }).then(res => {
      if (res.code === 0) {
        if (res.data.pricingMethod === 'THRESHOLD_FREE') {
          let { thresholdPrice, payPrice } = res.data.freightTemplateChildDetailVo
          formRef.current.setFieldsValue({
            ...res.data,
            thresholdPrice: Decimal(thresholdPrice).div(Decimal(100)).toNumber().toFixed(2),
            payPrice: Decimal(payPrice).div(Decimal(100)).toNumber().toFixed(2),
            isDefault: res.data.isDefault ? res.data.isDefault : 0
          })
        } else {
          console.log(res.data.isDefault);
          formRef.current.setFieldsValue({ ...res.data, isDefault: res.data.isDefault ? res.data.isDefault : 0 })
        }
        if (res.data.storeCityConfigVo) {
          setSelectArea({ areaId: res.data.storeCityConfigVo.cannotDeliveryAreaId, area: res.data.storeCityConfigVo.cannotDeliveryArea })
          setCity({ areaId: res.data.storeCityConfigVo.cannotDeliveryAreaId, area: res.data.storeCityConfigVo.cannotDeliveryArea })
        } else {
          setSelectArea([])
        }
      }
    })
  }
  useEffect(() => {
    async function init() {
      await getStoreInfo()
      // console.log(freightTemplateId,mode);
      if (freightTemplateId && (mode == 'edit' || mode == 'view')) {
        await getData()
      }
    }
    init()
  }, [])

  useEffect(() => {
    setCity(selectArea)
  }, [selectArea])

  useEffect(() => {
    if (cityModal) {
      areaRef.current.setKeys(selectArea)
    }
  }, [cityModal])
  const getStoreInfo = () => {
    apiStoreInfo().then(res => {
      console.log(res, 'res');
      if (res.code == 0) {
        if (res.data.isProprietary === 'Y') {
          setIsProprietary(res.data.isProprietary)
        }
      }
    })
  }
  const onFinish = async (v) => {
    let freightTemplateChildDTO = undefined
    if (v.pricingMethod === 'THRESHOLD_FREE') {
      freightTemplateChildDTO = {
        thresholdPrice: v.thresholdPrice * 100,
        payPrice: v.payPrice * 100,
      }
    }
    let cannotDeliveryArea = undefined, cannotDeliveryAreaId = undefined
    if (v.storeCityConfigVo) {
      cannotDeliveryAreaId = v.storeCityConfigVo.areaId
      cannotDeliveryArea = v.storeCityConfigVo.area
    }
    delete v.storeCityConfigVo
    delete v.thresholdPrice
    delete v.payPrice
    let params = { ...v, cannotDeliveryAreaId, cannotDeliveryArea, freightTemplateChildDTO }
    setLoading(true)
    await freightTemplateAddOrEdit({ ...params, freightTemplateId }).then(res => {
      if (res.code === 0) {
        message.success('保存成功')
        // getData()
        navigate(-1)

      } else {
        setLoading(false)

      }
    }).catch(err => {
      setLoading(false)

    })
  }
  const cityCheck = () => {
    setCityModal(true)
  }
  // 确认选择不可配送城市
  const locationSave = async () => {
    let areaInfo = areaRef.current.selectedRowKeys
    if (areaInfo) {
      setSelectArea(areaInfo)
      formRef.current.setFieldsValue({ storeCityConfigVo: areaInfo })
    }
    setCityModal(false)
  }
  // 取消关闭弹窗
  const locationCancel = () => {
    areaRef.current.cancel(selectArea)
    setCityModal(false)
  }
  return (
    <div className='wrap-box wrap-box-content'>
      <GoBack title={'运费模板'} />
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        ref={formRef}
        onFinish={onFinish}
        style={{ marginTop: 20 }}
        initialValues={{
          isDefault: 0
        }}
      >
        <Form.Item label="模板名称" name="freightTemplateName" rules={[{ required: true }]} extra={<span style={{ color: 'red' }}>运费模板名称将会显示在APP、小程序端的商品详情页，请谨慎填写</span>}>
          <Input style={{ width: 200 }} maxLength={15} />
        </Form.Item>
        <Form.Item label="运费设置" name="pricingMethod" style={{ marginBottom: 20 }} rules={[{ required: true, message: '请选择运费设置' }]} >
          <Radio.Group >
            <Space direction="vertical">
              <Radio value={'FREE'}>包邮</Radio>
              <Radio value={'THRESHOLD_FREE'}> 门槛包邮 </Radio>
            </Space>
          </Radio.Group>
        </Form.Item>
        <Form.Item name={'freightTemplateChildDTO'}>
          <Form.Item
            wrapperCol={{ offset: 2 }}
            shouldUpdate={(prevValues, currentValues) => prevValues.pricingMethod !== currentValues.pricingMethod}
          >
            {({ getFieldValue }) => {
              return getFieldValue('pricingMethod') === 'THRESHOLD_FREE' && <div style={{ display: "flex", alignItems: "baseline" }}>
                <span >单笔订单商品实付满</span>
                <Form.Item name="thresholdPrice"
                  rules={[{ required: true, message: '请输入包邮门槛金额' }]}
                  style={{ marginBottom: 0 }}
                >
                  <InputNumber controls={false} precision={2} min={0.01} max={99999.99} style={{ width: 100, margin: '0 7px' }} />
                </Form.Item>
                <span>元包邮,否则需另付</span>
                <Form.Item name="payPrice"
                  rules={[{ required: true, message: '请输入不满门槛另付邮费金额' }]}
                  style={{ marginBottom: 0 }}
                >
                  <InputNumber controls={false} precision={2} min={0.01} max={99999.99} style={{ width: 100, margin: '0 7px' }} />
                </Form.Item>
                <span>元邮费</span>
              </div>
            }}
          </Form.Item>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 2 }} name='storeCityConfigVo'>
          <div>
            <Button type='link' onClick={cityCheck}>不支持配送地区</Button>
            <span>{city && `${city.area ? city.area + '以及' : ""}`}</span>境外地区不可配送
          </div>
        </Form.Item>
        {
          isProprietary === 'Y' && <Form.Item label="是否默认" name="isDefault">
            <Radio.Group disabled={mode == 'view'}>
              <Radio value={0}>否</Radio>
              <Radio value={1}>是</Radio>
            </Radio.Group>
          </Form.Item>
        }

        <Form.Item style={{ display: 'flex', justifyContent: 'center' }}>
          {
            mode !== 'view' ? <TheButton haspermi={['goodsManagement:freightTemplate:save']} htmlType="submit" loading={loading}>保存</TheButton> : null
          }
        </Form.Item>
      </Form>
      <Modal title="城市地区" open={cityModal} width={'45%'} onOk={locationSave} onCancel={locationCancel} >
        <TheLocations ref={areaRef} selectArea={selectArea} defaultValue={selectArea} />
      </Modal>
    </div >
  )
}
